package com.meiyu.live.tv.audience;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.netease.neliveplayer.NELivePlayer;
import com.netease.neliveplayer.NEMediaPlayer;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver;
import com.netease.nimlib.sdk.chatroom.constant.MemberType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomResultData;
import com.umeng.socialize.UMShareAPI;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.BaseApplication;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.FocusEvent;
import com.meiyu.live.eventbus.RechargeEvent;
import com.meiyu.live.eventbus.WinEvent;
import com.meiyu.live.eventbus.YazhuEvent;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.BoughtParams;
import com.meiyu.live.net.param.GiftParams;
import com.meiyu.live.net.param.GointoGameParams;
import com.meiyu.live.net.param.GointoRoomParams;
import com.meiyu.live.net.param.PostbarrageParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.CoinsResponse;
import com.meiyu.live.net.response.DealResponse;
import com.meiyu.live.net.response.GointoRoomResponse;
import com.meiyu.live.net.response.LiveGiftResponse;
import com.meiyu.live.net.response.StringRemarkResponse;
import com.meiyu.live.popj.Anchor;
import com.meiyu.live.popj.Gift;
import com.meiyu.live.popj.GiftForLive;
import com.meiyu.live.popj.GointoRoom;
import com.meiyu.live.popj.Hookup;
import com.meiyu.live.popj.LiveRoom;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.popj.RelationInfo;
import com.meiyu.live.popj.RoomDanmuMessage;
import com.meiyu.live.popj.RoomMessage;
import com.meiyu.live.popj.UrlParams;
import com.meiyu.live.tv.utils.ChatRoomMessageParser;
import com.meiyu.live.tv.widget.AtmosphereView;
import com.meiyu.live.tv.widget.DanmuShowView;
import com.meiyu.live.tv.widget.GameListView;
import com.meiyu.live.tv.widget.GiftGifShowView;
import com.meiyu.live.tv.widget.GiftSendView;
import com.meiyu.live.tv.widget.GiftShowView;
import com.meiyu.live.tv.widget.InputView;
import com.meiyu.live.tv.widget.PrivateMessageView;
import com.meiyu.live.tv.widget.RoomManageListPopwindow;
import com.meiyu.live.tv.widget.RoomMessageAdapter;
import com.meiyu.live.tv.widget.TvTitleView;
import com.meiyu.live.ui.login.LoginActivity;
import com.meiyu.live.util.DisplayUtils;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.AppointDialog;
import com.meiyu.live.widget.GamePopupwind;
import com.meiyu.live.widget.RoomManageDialog;
import com.meiyu.live.widget.ShareDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

public class AudienceActivity extends BaseActivity implements OnClickListener {
    public final static String TAG = "AudienceActivity";

    public final static String ROOM_ID = "room_id";
    public final static String ANCHOR_ID = "anchor_id";
    public final static String ANCHOR_NAME = "anchor_name";
    public final static String ANCHOR_AVATAR = "anchor_avatar";
    public final static String VIDEO_PATH = "videoPath";

    //用于hookup跳转
    public final static String START_MODE = "start_mode";
    public final static String SCREENING_ID = "screening_id";
    public final static String VERIFY_ID = "verify_id";
    public final static String UNIQUE_ID = "unique_id";

    public final static int STATE_NORMAL = 0;
    public final static int STATE_INPUT_MESSAGE = 1;
    public final static int STATE_PRIVATE_MESSAGE = 2;
    public final static int STATE_SELECT_GIFT = 3;
    public final static int STATE_HIDE = 4;
    public final static int STATE_GAME = 5;
    public final static int STATE_NIUNIU = 6;

    private LayoutInflater inflater;
    private NEVideoView mVideoView;  //用于画面显示
    private View mBuffer; //用于指示缓冲状态
    private View btn_chat, btn_message, btn_gift, btn_share, btn_game, iv_message_flag;
    private ImageView btn_hide;
    private View layout_ui;
    private ImageView btn_manage;
    private View layout_bottom_btn;
    private TvTitleView tvTitleView;
    private GiftGifShowView giftGifShowView;
    private GiftShowView giftShowView;
    private DanmuShowView danmuShowView;
    private InputView inputView;
    private PrivateMessageView privateMessageView;
    private GiftSendView giftSendView;
    private GameListView gameListView;
    private ListView listView_message;
    private RoomMessageAdapter messageAdapter;
    private ChatRoomMessageParser chatRoomMessageParser;
    private RoomManageListPopwindow roomManageListPopwindow;
    private AtmosphereView atmosphere_view;

    private ShareDialog shareDialog;
    private EnterChatRoomData data;

    private String mVideoPath; //文件路径
    private long room_id; //房间id
    private long anchor_id; //主播id
    private String room_des; //房间描述
    private long unique_id;
    private boolean isManager = false;//是否是场控
    private boolean isMute = false;//是否被禁言
    private String anchor_name; //主播名字
    private String anchor_avatar; //主播头像
    private long anchorCoins, myCoins;
    private long saveJionTime;//记录进入直播间的时间
    private boolean hasLightOn = false;

    private int currentState = STATE_NORMAL;

    private boolean isGoin = false;

    //hookup
    private int start_mode = 0;
    private int screening_id;
    private long verify_id;

    private GointoRoomResponse result;
    /**
     * "livestream","videoondemand"
     */
    private String mMediaType = "livestream"; //媒体类型
    private boolean mHardware = true;
    private boolean pauseInBackgroud = false;

    private NEMediaPlayer mMediaPlayer = new NEMediaPlayer();

    private Handler handler = new Handler();

    private List<RoomMessage> roomMessageList = new ArrayList<>();

    private GamePopupwind gamePopupwind;

    public static void start(Context context, LiveRoom bean) {
        if (!UserConfig.getInstance().isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return;
        }
        Intent intent = new Intent(context, AudienceActivity.class);
        intent.putExtra(ROOM_ID, bean.getRoom_id());
        intent.putExtra(ANCHOR_ID, bean.getAnchor_id());
        intent.putExtra(SCREENING_ID, bean.getScreening_id());
        intent.putExtra(VERIFY_ID, bean.getVerify_id());
        intent.putExtra(VIDEO_PATH, bean.getRtmp_Pull_Url());
        intent.putExtra(ANCHOR_NAME, bean.getAnchor_name());
        intent.putExtra(ANCHOR_AVATAR, bean.getAvatar());
        context.startActivity(intent);
    }

    public static void start(Context context, UrlParams params) {
        if (!UserConfig.getInstance().isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return;
        }
        Intent intent = new Intent(context, AudienceActivity.class);
        intent.putExtra(SCREENING_ID, params.getScreening_id());
        intent.putExtra(UNIQUE_ID, params.getUnique_id());
        UserConfig.getInstance().setParams(null);
        context.startActivity(intent);
    }

    public static void start(Context context, Hookup bean) {
        if (!UserConfig.getInstance().isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return;
        }
        Intent intent = new Intent(context, AudienceActivity.class);
        intent.putExtra(START_MODE, 1);
        intent.putExtra(ANCHOR_ID, bean.getAnchor_id());
        intent.putExtra(SCREENING_ID, bean.getScreening_id());
        intent.putExtra(VERIFY_ID, bean.getVerify_id());
        intent.putExtra(ANCHOR_NAME, bean.getAnchor_name());
        intent.putExtra(ANCHOR_AVATAR, bean.getAvatar());
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "on create");
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_player);
        saveJionTime = System.currentTimeMillis();

        //接收MainActivity传过来的参数
        start_mode = getIntent().getIntExtra(START_MODE, 0);
        screening_id = getIntent().getIntExtra(SCREENING_ID, 0);
        verify_id = getIntent().getLongExtra(VERIFY_ID, 0);
        unique_id = getIntent().getLongExtra(UNIQUE_ID, 0);
        //
        mVideoPath = getIntent().getStringExtra(VIDEO_PATH);
        room_id = getIntent().getLongExtra(ROOM_ID, 0);
        anchor_id = getIntent().getLongExtra(ANCHOR_ID, 0);
        anchor_name = getIntent().getStringExtra(ANCHOR_NAME);
        anchor_avatar = getIntent().getStringExtra(ANCHOR_AVATAR);
        Log.d(TAG, "videoPath = " + mVideoPath);

        Intent intent = getIntent();
        String intentAction = intent.getAction();
        if (!TextUtils.isEmpty(intentAction) && intentAction.equals(Intent.ACTION_VIEW)) {
            mVideoPath = intent.getDataString();
            Log.d(TAG, "videoPath = " + mVideoPath);
        }

        if (!TextUtils.isEmpty(mVideoPath) && mVideoPath.startsWith("http")) {
            mMediaType = "videoondemand";
        }

        //TODO test,delete when release
//        if (mVideoPath == null || !mVideoPath.startsWith("rtmp://")) {
//            mVideoPath = "rtmp://v5886108b.live.126.net/live/15853282a0654e1788a127c7ecf374fd";
//        }

        init();

        setState(STATE_NORMAL);

        if (start_mode == 0) {
//            startPlay();
            goingTo();
        } else {
            goingTo();
        }
    }

    private void goingTo() {
        GointoRoomParams gointoRoomParams;
        if (unique_id != 0) {
            gointoRoomParams = new GointoRoomParams(unique_id, screening_id);
        } else {
            gointoRoomParams = new GointoRoomParams(anchor_id, screening_id, verify_id);
        }
        //进入直播间
        request(gointoRoomParams,
                GointoRoomResponse.class, new Response.Listener<GointoRoomResponse>() {
                    @Override
                    public void onResponse(GointoRoomResponse gointoRoomResponse) {
                        if (gointoRoomResponse != null) {
                            if (gointoRoomResponse.getStatusCode() == Constant.StatusCode_Success) {//直接进直播
                                GointoRoom gointoRoom = gointoRoomResponse.getRoom();
                                room_des = gointoRoom.getDescription();
                                Anchor anchor = gointoRoomResponse.getAnchor();
                                if (gointoRoom != null && anchor != null) {
                                    mVideoPath = gointoRoom.getPull_url();
                                    result = gointoRoomResponse;
                                    room_id = anchor.getRoom_id();
                                    anchor_id = gointoRoom.getAnchor_id();
                                    anchor_name = anchor.getName();
                                    anchor_avatar = anchor.getAvatar();
                                    tvTitleView.setAuthorInfo(anchor_name, anchor_avatar);
                                    anchorCoins = anchor.getIncome();
                                    tvTitleView.setCoins(anchorCoins);
                                    tvTitleView.setNeteaseId(anchor.getNet_ease());
                                    tvTitleView.setCuteCode(anchor.getCutecode() + "");
                                    tvTitleView.setIsFollow(gointoRoomResponse.is_follow());

                                    getGiftlistData();
                                    getCoinsData();
                                    startPlay();
                                    startPostAddRobotTask();
                                } else {
                                    onFinishLive();
                                }
                            } else if (gointoRoomResponse.getStatusCode() == 3) {//需要认购
                                startAppoint();
                            } else {//已经结束
                                onFinishLive();
                            }
                        } else {
                            onFinishLive();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        onFinishLive();
                    }
                });
    }

    private void startAppoint() {
        AppointDialog appointDialog = new AppointDialog(this);
        Anchor anchor = new Anchor();
        anchor.setAnchor_id(anchor_id);
        anchor.setVerify_id(verify_id);
        anchor.setShares_per_one(10);
        appointDialog.setData(anchor);
        appointDialog.setAppointDialogListener(new AppointDialog.AppointDialogListener() {
            @Override
            public void onBuy(long verify_id, int cost) {
                request(new BoughtParams(verify_id, cost), BaseResponse.class, new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse onlyStatusResponse) {
                        if (onlyStatusResponse != null) {
                            if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                                ToastUtil.show("购买成功");
                                goingTo();
                            } else if (onlyStatusResponse.getStatusCode() == 3) {
                                ToastUtil.show("购买失败，余额不足");
                                finish();
                            } else {
                                ToastUtil.show("购买失败");
                                finish();
                            }
                        } else {
                            ToastUtil.show("购买失败");
                            finish();
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        appointDialog.show();
    }

    private void startPlay() {
        mVideoView.setVideoPath(mVideoPath);
        mVideoView.requestFocus();
        mVideoView.start();
        initIM();
    }

    private void init() {


        inflater = LayoutInflater.from(this);

        btn_chat = findViewById(R.id.btn_chat);
        btn_chat.setOnClickListener(this);
        btn_message = findViewById(R.id.btn_message);
        btn_message.setOnClickListener(this);
        btn_gift = findViewById(R.id.btn_gift);
        btn_gift.setOnClickListener(this);
        btn_game = findViewById(R.id.btn_game);
        btn_game.setOnClickListener(this);
        btn_share = findViewById(R.id.btn_share);
        btn_share.setOnClickListener(this);
        btn_hide = (ImageView) findViewById(R.id.btn_hide);
        btn_hide.setOnClickListener(this);
        iv_message_flag = findViewById(R.id.iv_message_flag);
        btn_manage = (ImageView) findViewById(R.id.btn_room_manage);
        btn_manage.setOnClickListener(this);
        layout_ui = findViewById(R.id.layout_ui);

        mBuffer = findViewById(R.id.buffering_prompt);

        mVideoView = (NEVideoView) findViewById(R.id.video_view);

        if (mMediaType.equals("livestream")) {
            mVideoView.setBufferStrategy(0); //直播低延时
        } else {
            mVideoView.setBufferStrategy(1); //点播抗抖动
        }
//        mVideoView.setMediaController(mMediaController);
        mVideoView.setBufferPrompt(mBuffer);
        mVideoView.setMediaType(mMediaType);
        mVideoView.setHardwareDecoder(mHardware);
        mVideoView.setPauseInBackground(pauseInBackgroud);
        mMediaPlayer.setLogLevel(NEMediaPlayer.IJK_LOG_SILENT); //设置log级别
//        mVideoView.requestFocus();
//        mVideoView.start();
        Log.d(TAG, "Version = " + mMediaPlayer.getVersion()); //获取解码库版本号
        mVideoView.setOnCompletionListener(new NELivePlayer.OnCompletionListener() {
            @Override
            public void onCompletion(NELivePlayer neLivePlayer) {
                onFinishLive();
            }
        });

        tvTitleView = (TvTitleView) findViewById(R.id.view_tvtitle);
        tvTitleView.setOnTvTitleViewListener(new TvTitleView.OnTvTitleViewClickListener() {
            @Override
            public void onBack() {
                finish();
            }

            @Override
            public void onClickPrivateMessage(String neteaseId) {
                privateMessageView.startPrivateMessage(neteaseId);
                setState(STATE_PRIVATE_MESSAGE);
            }

            @Override
            public void onClickManage() {

            }
        });
//        tvTitleView.setAuthorInfo(anchor_name, anchor_avatar);
        tvTitleView.setAnchorId(anchor_id);
        tvTitleView.setShowFollowButton(true);

        layout_bottom_btn = findViewById(R.id.layout_bottom_btn);
        giftGifShowView = (GiftGifShowView) findViewById(R.id.giftGifShowView);
        giftShowView = (GiftShowView) findViewById(R.id.giftShowView);
        giftShowView.setOnGiftShowListener(new GiftShowView.OnGiftShowListener() {
            @Override
            public void onGiftShowFinish(Gift gift) {
                final RoomMessage roomMessage = new RoomMessage();
                roomMessage.setType(1);
                roomMessage.setName(gift.name);
                roomMessage.setAvatar(gift.icon);
                roomMessage.setUser_id(gift.user_id);
                roomMessage.setNet_ease_id(gift.net_ease_id);
                roomMessage.setLevel(gift.level);
                if (gift.gift_count == 1) {
                    roomMessage.setContent("送了一个" + gift.gift_name);
                } else {
                    roomMessage.setContent("送了" + gift.gift_count + "个" + gift.gift_name);
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }
        });
        danmuShowView = (DanmuShowView) findViewById(R.id.danmuShowView);
        inputView = (InputView) findViewById(R.id.inputView);
        inputView.setOnInputListener(new InputView.OnInputListener() {
            @Override
            public void onSend(String text, boolean isDanmu) {
                if (isMute) {
                    ToastUtil.show("您已被禁言，不能发言");
                    return;
                }
                if (isDanmu) {
                    sendDanmuMessage(text);
                } else {
                    sendRoomMessage(text, ChatRoomMessageParser.TYPE_ROOM_MESSAGE);
                }
                setState(STATE_NORMAL);
            }
        });
        privateMessageView = (PrivateMessageView) findViewById(R.id.privateMessageView);
        privateMessageView.setListener(new PrivateMessageView.PrivateMessageViewListener() {
            @Override
            public void onBack() {
                setState(STATE_NORMAL);
            }

            @Override
            public void onNewMessage() {
                if (currentState != STATE_PRIVATE_MESSAGE) {
                    iv_message_flag.setVisibility(View.VISIBLE);
                }
            }
        });
        giftSendView = (GiftSendView) findViewById(R.id.giftSendView);
        giftSendView.setGiftSendViewListener(new GiftSendView.GiftSendViewListener() {
            @Override
            public void onSendGift(GiftForLive giftForLive) {
                sendGift(giftForLive);
            }
        });

        gameListView = (GameListView) findViewById(R.id.gameListView);
        gameListView.setOnStartGameListener(new GameListView.StartGameListener() {
            @Override
            public void onStartGame() {
                goinGame(true);
            }
        });

        gamePopupwind = (GamePopupwind) findViewById(R.id.gamePopupwind);
        gamePopupwind.setOnHideListener(new GamePopupwind.OnHideListener() {
            @Override
            public void onHide() {
                setState(STATE_NORMAL);
            }
        });
        gamePopupwind.init(2);

        listView_message = (ListView) findViewById(R.id.listview_message);
        messageAdapter = new RoomMessageAdapter(this, roomMessageList);
        messageAdapter.setOnNameClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isManager) {
                    int p = (int) v.getTag();
                    RoomMessage message = roomMessageList.get(p);
                    RoomManageDialog dialog = new RoomManageDialog(AudienceActivity.this);
                    dialog.setIsAnchor(false);
                    dialog.setData(room_id, message);
                    dialog.show();
                }
            }
        });
        listView_message.setAdapter(messageAdapter);

        atmosphere_view = (AtmosphereView) findViewById(R.id.atmosphere_view);
        atmosphere_view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!hasLightOn) {
                    hasLightOn = true;
                    sendRoomMessage("", ChatRoomMessageParser.TYPE_ATMOSPHERE);
                }
            }
        });
    }

    private void initIM() {
        data = new EnterChatRoomData(room_id + "");
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (personalInfo != null && relationInfo != null) {
            data.setNick(personalInfo.getName());
            data.setAvatar(personalInfo.getAvatar());
            HashMap<String, Object> map = new HashMap<>();
            map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
            map.put("user_id", personalInfo.getId() + "");
            map.put("icon", personalInfo.getAvatar());
            int level = relationInfo.getLevel();
            map.put("level", level);
            map.put("nick", personalInfo.getName());
            data.setExtension(map);
            data.setNotifyExtension(map);
        }
        NIMClient.getService(ChatRoomService.class).enterChatRoom(data)
                .setCallback(callback);

        //初始化消息解析器
        chatRoomMessageParser = new ChatRoomMessageParser(new ChatRoomMessageParser.ChatRoomMessageParseListener() {
            @Override
            public void onGift(Gift gift) {
                if (gift.is_dynamic) {
                    giftGifShowView.addGif(gift);
                    final RoomMessage roomMessage = new RoomMessage();
                    roomMessage.setType(1);
                    roomMessage.setName(gift.name);
                    roomMessage.setAvatar(gift.icon);
                    roomMessage.setUser_id(gift.user_id);
                    roomMessage.setNet_ease_id(gift.net_ease_id);
                    roomMessage.setLevel(gift.level);
                    roomMessage.setContent("送了一个" + gift.gift_name);
                    roomMessageList.add(roomMessage);
                    messageAdapter.notifyDataSetChanged();
                    listView_message.setSelection(listView_message.getBottom());
                } else {
                    giftShowView.addGift(gift);
                }
                anchorCoins += gift.gift_scale * gift.gift_price * gift.gift_count * 10 / 100;
                tvTitleView.setCoins(anchorCoins);
            }

            @Override
            public void onMessage(RoomMessage roomMessage) {
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onEnterMessage(RoomMessage roomMessage, boolean isTargetMe) {
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
                tvTitleView.addMember(room_id, roomMessage.getOperatorNeteaseId());
            }

            @Override
            public void onExitMessage(RoomMessage roomMessage) {
                tvTitleView.removeMember(roomMessage.getOperatorNeteaseId());
            }

            @Override
            public void onDanmuMessage(RoomDanmuMessage roomDanmuMessage) {
                danmuShowView.addRoomDanmuMessage(roomDanmuMessage);
            }

            @Override
            public void onFinishLive() {
                AudienceActivity.this.onFinishLive();
            }

            @Override
            public void onSetManager(RoomMessage roomMessage, boolean isManager, boolean isTargetMe) {
                if (roomManageListPopwindow != null) {
                    if (isManager) {
                        roomManageListPopwindow.addManager(roomMessage.getTargetNeteaseId());
                        roomManageListPopwindow.removeMute(roomMessage.getTargetNeteaseId());
                    } else {
                        roomManageListPopwindow.removeManager(roomMessage.getTargetNeteaseId());
                    }
                }
                if (isTargetMe) {
                    setIsManager(isManager);
                    if (isManager) {
                        setIsMute(false);
                    }
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onSetMute(RoomMessage roomMessage, boolean isMute, boolean isTargetMe) {
                if (roomManageListPopwindow != null) {
                    if (isMute) {
                        roomManageListPopwindow.addMute(roomMessage.getTargetNeteaseId());
                        roomManageListPopwindow.removeManager(roomMessage.getTargetNeteaseId());
                    } else {
                        roomManageListPopwindow.removeMute(roomMessage.getTargetNeteaseId());
                    }
                }
                if (isTargetMe) {
                    setIsMute(isMute);
                    if (isMute) {
                        setIsManager(false);
                    }
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onLightOn(RoomMessage roomMessage) {
                atmosphere_view.addOne();
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onGameDeal() {
                goinGame(false);
            }

            @Override
            public void onGameBet() {
                updateYazhu();
            }

        });
    }

    private void goinGame(boolean isClick) {

        if (currentState != STATE_NIUNIU && !isClick && isGoin) {
            return;
        }
        if (isClick || !isGoin) {
            setState(STATE_NIUNIU);

        }
        if (!isGoin) {
            isGoin = true;
        }

        request(new GointoGameParams(anchor_id), DealResponse.class, new Response.Listener<DealResponse>() {
            @Override
            public void onResponse(DealResponse baseResponse) {

                if (baseResponse.getStatusCode() == 6) {
                    long start_time = baseResponse.getRemark().getStart_at();
                    //// 弹出游戏窗口 getStart_at为游戏开始时间（格式为时间戳），
                    /// 开始倒计时时间为15-（当前时间-开始时间），如果大于0则开始计时，否则为游戏未开始界面
                    long end_time = System.currentTimeMillis();
                    int spend_time = (int) (end_time / 1000 - start_time);
                    if (spend_time <= 15) {
                        gamePopupwind.setNiu_sid(baseResponse.getRemark().getNiu_sid());
                        gamePopupwind.setTimeParam((15 - spend_time) * 1000);
                        gamePopupwind.setYazhu(baseResponse.getBets());
                    } else {
                        gamePopupwind.init(2);
                    }

                } else {
//                    gamePopupwind.init(2);
                }
            }
        });


    }

    private void updateYazhu() {
        request(new GointoGameParams(anchor_id), DealResponse.class, new Response.Listener<DealResponse>() {
            @Override
            public void onResponse(DealResponse baseResponse) {

                if (baseResponse.getStatusCode() == 6) {
                    gamePopupwind.setYazhu(baseResponse.getBets());
                }
            }
        });
    }

    RequestCallback callback = new RequestCallback<EnterChatRoomResultData>() {
        @Override
        public void onSuccess(EnterChatRoomResultData param) {
            Log.e(TAG, "进入聊天室成功");
            NIMClient.getService(ChatRoomServiceObserver.class)
                    .observeReceiveMessage(incomingChatRoomMsg, true);
            tvTitleView.updateRoomMembers(room_id);
            ChatRoomMember member = param.getMember();
            if (member != null) {
                setIsManager(member.getMemberType() == MemberType.ADMIN);
                setIsMute(member.isMuted());
            }
//            getMyRoomInfo();
        }

        @Override
        public void onFailed(int code) {
            Log.e(TAG, "进入聊天室失败:" + code);
            BaseApplication.getApp().reEnterRoom(callback, data);

        }

        @Override
        public void onException(Throwable exception) {
            Log.e(TAG, "进入聊天室出错");
        }
    };

    private Observer<List<ChatRoomMessage>> incomingChatRoomMsg = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            for (ChatRoomMessage message : messages) {
                chatRoomMessageParser.parse(message);
            }
        }
    };


    //获取我的房间用户状态
    private void getMyRoomInfo() {

        ArrayList<String> accounts = new ArrayList<>();
        accounts.add(UserConfig.getInstance().getNet_ease());
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomMembersByIds(room_id + "", accounts)
                .setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {

                    @Override
                    public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                        if (result != null && result.size() > 0) {
                            ChatRoomMember member = result.get(0);
                            setIsManager(member.getMemberType() == MemberType.ADMIN);
                            setIsMute(member.isMuted());
                        }
                    }
                });
    }

//    private void getValidateData() {
//        request(new ValidateParams(anchor_id, mVideoPath), ValidateResponse.class, new Response.Listener<ValidateResponse>() {
//            @Override
//            public void onResponse(ValidateResponse validateResponse) {
//                if (validateResponse != null) {
//                    if (validateResponse.getStatusCode() != Constant.StatusCode_Success) {
//                        onFinishLive();
//                    } else {
//                        anchorCoins = validateResponse.getIncome();
//                        tvTitleView.setCoins(anchorCoins);
//                        tvTitleView.setNeteaseId(validateResponse.getNetEase());
//                    }
//                }
//            }
//        });
//    }

//    /**
//     * 获取是否关注
//     */
//    private void getRelationData() {
//        request(new PersonalParams(anchor_id + ""), PersonalResponse.class, new Response.Listener<PersonalResponse>() {
//            @Override
//            public void onResponse(PersonalResponse personalResponse) {
//                if (personalResponse != null) {
//                }
//            }
//        });
//    }

    private void getGiftlistData() {
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.UrlParams.LIVEGIFTS);
        request(b, LiveGiftResponse.class, new Response.Listener<LiveGiftResponse>() {
            @Override
            public void onResponse(LiveGiftResponse liveGiftResponse) {
                if (liveGiftResponse != null) {
                    giftSendView.setData(liveGiftResponse.getHash());
                }
            }
        });
    }

    private void getCoinsData() {
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.UrlParams.MY_COINS);
        request(b, CoinsResponse.class, new Response.Listener<CoinsResponse>() {
            @Override
            public void onResponse(CoinsResponse coinsResponse) {
                if (coinsResponse != null) {
                    myCoins = coinsResponse.getCarrots();
                    giftSendView.setCoins(myCoins);
                    gamePopupwind.setCoins((int) myCoins);
                }
            }
        });
    }


    private void startPostAddRobotTask() {
        if (handler != null) {
            handler.postDelayed(postAddRobotTask, 30 * 1000);
        }
    }

    private void stopPostAddRobotTask() {
        if (handler != null) {
            handler.removeCallbacks(postAddRobotTask);
        }
    }

    private Runnable postAddRobotTask = new Runnable() {
        @Override
        public void run() {
            postDurationData();
            startPostAddRobotTask();
        }
    };

    private void postDurationData() {
        request(new BaseBodyParams(Constant.UrlParams.HEARTBEAT), BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

//    private void postDurationData(long duration) {
//        GiftParams giftParams = new GiftParams(anchor_id, duration / 1000);
//        giftParams.setUrl(Constant.UrlParams.ADDDURATION);
//        request(giftParams, OnlyStatusResponse.class, new Response.Listener<OnlyStatusResponse>() {
//            @Override
//            public void onResponse(OnlyStatusResponse onlyStatusResponse) {
//
//            }
//        });
//    }

    @Override
    protected void onStop() {
        Log.d(TAG, "AudienceActivity onStop");
        super.onStop();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "AudienceActivity onPause");

        if (pauseInBackgroud) {
            mVideoView.pause(); //锁屏时暂停
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "AudienceActivity onDestroy");
        stopPostAddRobotTask();
        mVideoView.release_resource();
        EventBus.getDefault().unregister(this);

        //停止监听聊天
        NIMClient.getService(ChatRoomServiceObserver.class)
                .observeReceiveMessage(incomingChatRoomMsg, false);
        //退出聊天室
        NIMClient.getService(ChatRoomService.class).exitChatRoom(room_id + "");

        super.onDestroy();
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "AudienceActivity onStart");
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "AudienceActivity onResume");
        if (pauseInBackgroud && !mVideoView.isPaused()) {
            mVideoView.start(); //锁屏打开后恢复播放
        }
        super.onResume();
    }

    @Override
    protected void onRestart() {
        Log.d(TAG, "AudienceActivity onRestart");
        super.onRestart();
    }

    public void onEvent(FocusEvent event) {
        if (event.userId == anchor_id) {
            tvTitleView.setIsFollow(event.isFocus);
            if (event.isFocus) {
                sendRoomMessage("关注了主播", ChatRoomMessageParser.TYPE_ROOM_MESSAGE);
            }
        }
    }

    public void onEvent(YazhuEvent event) {
        sendDealMessage(chatRoomMessageParser.TYPE_GAME_BET);
    }

    private void sendDealMessage(int type) {
        // 创建文本/弹幕消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", type);
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                System.currentTimeMillis() + "" // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
    }

    public void onEvent(RechargeEvent event) {
        getCoinsData();
    }

    public void onEvent(WinEvent event) {
        String msg = "在牛牛游戏中赢了" + event.getWin() + "钻石";
        sendRoomMessage(msg, ChatRoomMessageParser.TYPE_ROOM_MESSAGE);
    }

    @Override
    public void onBackPressed() {
        if (currentState != STATE_NORMAL) {
            setState(STATE_NORMAL);
        } else {
            super.onBackPressed();
        }
    }

    boolean hasFinish = false;

    private void onFinishLive() {
        if (!hasFinish) {
            hasFinish = true;
            Intent intent = new Intent(this, AudienceFinishActivity.class);
            intent.putExtra(AudienceFinishActivity.ANCHOR_ID, anchor_id);
            intent.putExtra(AudienceFinishActivity.ANCHOR_NAME, anchor_name);
            intent.putExtra(AudienceFinishActivity.ANCHOR_AVATAR, anchor_avatar);
            intent.putExtra(AudienceFinishActivity.AUDIENCE_COUNT, tvTitleView.getMemberCount() + "");
            intent.putExtra(AudienceFinishActivity.AUDIENCE_IS_FOLLOW, tvTitleView.getIsFollow());
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void finish() {
//        postDurationData(System.currentTimeMillis() - saveJionTime);
        super.finish();
    }

    @Override
    public void onClick(View view) {
        if (view == btn_chat) {
            setState(STATE_INPUT_MESSAGE);
        } else if (view == btn_message) {
            setState(STATE_PRIVATE_MESSAGE);
        } else if (view == btn_game) {
            setState(STATE_GAME);
        } else if (view == btn_gift) {
            setState(STATE_SELECT_GIFT);
        } else if (view == btn_share) {
            if (shareDialog == null) {
                shareDialog = new ShareDialog(this,
                        anchor_name + "正在直播，快来支持一下吧！",
                        room_des,
                        anchor_avatar,
                        "http://mt.201.0110net.com/m/live.html?u=" + result.getAnchor().getUnique_id() + "&s=" + result.getRoom().getHookup_screening_id());
            }
            shareDialog.show();
        } else if (view == btn_hide) {
            if (currentState == STATE_HIDE) {
                setState(STATE_NORMAL);
            } else {
                setState(STATE_HIDE);
            }
        } else if (view == btn_manage) {
            if (roomManageListPopwindow == null) {
                roomManageListPopwindow = new RoomManageListPopwindow(AudienceActivity.this);
                roomManageListPopwindow.setIsAnchor(false);
                roomManageListPopwindow.updateData(room_id);
            }
            if (roomManageListPopwindow.isShowing()) {
                roomManageListPopwindow.dismiss();
            } else {
                int margin = DisplayUtils.dpToPixel(getApplicationContext(), 20);
                roomManageListPopwindow.showAsDropDown(tvTitleView.getLayoutMoney(), margin, margin);
            }
        }
    }

    private void setIsManager(boolean isManager) {
        this.isManager = isManager;
        btn_manage.setVisibility(isManager ? View.VISIBLE : View.GONE);
    }

    private void setIsMute(boolean isMute) {
        this.isMute = isMute;
//        btn_manage.setVisibility(isManager ? View.VISIBLE : View.GONE);
    }

    private void setState(int state) {
        switch (state) {
            case STATE_NORMAL:
                inputView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.VISIBLE);
                btn_hide.setVisibility(View.VISIBLE);
                atmosphere_view.setVisibility(View.VISIBLE);
                break;
            case STATE_INPUT_MESSAGE:
                gamePopupwind.setVisibility(View.GONE);
                giftShowView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                privateMessageView.setVisibility(View.GONE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                btn_hide.setVisibility(View.GONE);
                inputView.setVisibility(View.VISIBLE);
                showSoftInputFromWindow(inputView.getEditView());
                break;
            case STATE_PRIVATE_MESSAGE:
                iv_message_flag.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                giftShowView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.GONE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                privateMessageView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.GONE);
                layout_bottom_btn.setVisibility(View.GONE);
                btn_hide.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                break;
            case STATE_SELECT_GIFT:
                giftSendView.setVisibility(View.VISIBLE);
                gameListView.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                btn_hide.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                break;
            case STATE_HIDE:
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.GONE);
                listView_message.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                layout_bottom_btn.setVisibility(View.VISIBLE);
                btn_hide.setVisibility(View.VISIBLE);
                break;
            case STATE_GAME:
                gameListView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                btn_hide.setVisibility(View.GONE);
                break;
            case STATE_NIUNIU:
                gamePopupwind.setVisibility(View.VISIBLE);
                gameListView.setVisibility(View.GONE);
                giftSendView.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                btn_hide.setVisibility(View.GONE);
                atmosphere_view.setVisibility(View.GONE);
                break;
        }
        if (currentState != state) {
            if (currentState == STATE_HIDE) {
//                layout_ui.setVisibility(View.VISIBLE);
//                btn_hide.setImageResource(R.drawable.play_push_icon);
                setShowUI(true);
            } else if (state == STATE_HIDE) {
//                layout_ui.setVisibility(View.GONE);
//                btn_hide.setImageResource(R.drawable.play_pull_icon);
                setShowUI(false);
            }
        }
        currentState = state;
    }

    private static final long SHOW_HIDE_DURATION = 300;

    private void setShowUI(boolean isShow) {
        if (isShow) {
            AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
            alphaAnimation.setDuration(SHOW_HIDE_DURATION);
            alphaAnimation.setFillAfter(true);
            alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    layout_ui.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            RotateAnimation rotateAnimation = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(SHOW_HIDE_DURATION);
            rotateAnimation.setFillAfter(true);

            layout_ui.startAnimation(alphaAnimation);
            btn_hide.startAnimation(rotateAnimation);
        } else {
            AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
            alphaAnimation.setDuration(SHOW_HIDE_DURATION);
            alphaAnimation.setFillAfter(true);
            alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    layout_ui.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            RotateAnimation rotateAnimation = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(SHOW_HIDE_DURATION);
            rotateAnimation.setFillAfter(true);

            layout_ui.startAnimation(alphaAnimation);
            btn_hide.startAnimation(rotateAnimation);

        }
    }

    private void sendGift(final GiftForLive giftForLive) {
        if (isMute) {
            ToastUtil.show("您已被禁言，不能发送礼物");
            return;
        }
        final int cost = giftForLive.gift_count * giftForLive.getUnit_price();
        if (myCoins < cost) {
            ToastUtil.show("您的钻石余额不足！");
            return;
        }
        myCoins -= cost;
        giftSendView.setCoins(myCoins);
        sendGiftMessage(giftForLive);
        if (sendGiftRequestTask == null) {//没有缓冲的礼物任务
            sendGiftRequestTask = new SendGiftRequestTask(giftForLive);
            handler.postDelayed(sendGiftRequestTask, 2000);
        } else {
            if (sendGiftRequestTask.isSameGift(giftForLive)) {//是同一种礼物
                sendGiftRequestTask.addCount(giftForLive.gift_count);
                handler.removeCallbacks(sendGiftRequestTask);
                handler.postDelayed(sendGiftRequestTask, 2000);
            } else {
                handler.removeCallbacks(sendGiftRequestTask);
                sendGiftRequestTask.run();//立即发送上一个礼物的请求
                sendGiftRequestTask = new SendGiftRequestTask(giftForLive);
                handler.postDelayed(sendGiftRequestTask, 2000);
            }
        }
    }

    private SendGiftRequestTask sendGiftRequestTask;

    private class SendGiftRequestTask implements Runnable {

        public long send_gift_id = -1;
        public int count;
        private GiftForLive giftForLive;

        public SendGiftRequestTask(GiftForLive giftForLive) {
            this.giftForLive = giftForLive;
            send_gift_id = giftForLive.getId();
            count = giftForLive.gift_count;
        }

        public void addCount(int count) {
            this.count += count;
        }

        public boolean isSameGift(GiftForLive giftForLive) {
            return giftForLive.getId() == send_gift_id;
        }

        @Override
        public void run() {
            sendGiftRequestTask = null;
            GiftParams giftParams = new GiftParams(anchor_id, giftForLive.getId() + "", count + "");
            giftParams.setUrl(Constant.UrlParams.ADDGIFT);
            request(giftParams, StringRemarkResponse.class, new Response.Listener<StringRemarkResponse>() {
                @Override
                public void onResponse(StringRemarkResponse onlyStatusResponse) {
                    if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                        Integer remark = 0;
                        try {
                            remark = Integer.valueOf(onlyStatusResponse.getRemark());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        if (remark > 0) {
                            HashMap<String, Object> extraMap = new HashMap<>();
                            extraMap.put("value", remark);
                            sendRoomMessage("", ChatRoomMessageParser.TYPE_SYS_DANMU_MESSAGE, extraMap);
                            myCoins += remark;
                            giftSendView.setCoins(myCoins);
//                            ToastUtil.show("恭喜您获得了 " + remark + " 金币返还！");
                        }
                    } else if (onlyStatusResponse.getStatusCode() == 2) {
                        ToastUtil.show("您的钻石余额不足！");
                    }
                }
            });
        }
    }

    ;

    private void sendGiftMessage(GiftForLive giftForLive) {
        // 发送礼物
        HashMap<String, Object> map = new HashMap<>();
        map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
        map.put("user_id", UserConfig.getInstance().getLogingAccount());
        map.put("type", 2);
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            map.put("name", personalInfo.getName());
            map.put("icon", personalInfo.getAvatar());
        }
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            map.put("level", relationInfo.getLevel());
        }
        map.put("gift_type", giftForLive.getId() + "");
        map.put("gift_name", giftForLive.getName());
        map.put("gift_icon", giftForLive.getImage_url());
        map.put("gift_animation", giftForLive.getAnimation_url());
        map.put("gift_count", giftForLive.gift_count);
        map.put("gift_scale", giftForLive.getGift_scale());
        map.put("gift_price", giftForLive.getUnit_price());
        map.put("gift_is_dynamic", giftForLive.getIs_dynamic());

        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                "test message" + System.currentTimeMillis() // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
        chatRoomMessageParser.parse(message);
    }

    private void sendDanmuMessage(final String text) {
        int cost = Constant.Danmu_Price;
        if (myCoins < cost) {
            ToastUtil.show("您的钻石余额不足！");
            return;
        }
        myCoins -= cost;
        giftSendView.setCoins(myCoins);
        PostbarrageParams postbarrageParams = new PostbarrageParams(anchor_id, 1);
        request(postbarrageParams, BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {
                if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                    sendRoomMessage(text, ChatRoomMessageParser.TYPE_DANMU_MESSAGE);
                } else if (onlyStatusResponse.getStatusCode() == 2) {
                    ToastUtil.show("您的钻石余额不足！");
                } else {
                    ToastUtil.show("弹幕发送失败");
                }
            }
        });
    }

    private void sendRoomMessage(String text, int type) {
        sendRoomMessage(text, type, null);
    }

    private void sendRoomMessage(String text, int type, HashMap<String, Object> extraMap) {
        // 创建文本/弹幕消息
        HashMap<String, Object> map = new HashMap<>();
        if (extraMap != null && extraMap.size() > 0) {
            map.putAll(extraMap);
        }
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            map.put("name", personalInfo.getName());
            map.put("avatar", personalInfo.getAvatar());
        }
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            map.put("level", relationInfo.getLevel());
        }
        map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
        map.put("user_id", UserConfig.getInstance().getLogingAccount());
        map.put("type", type);
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                text // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
        chatRoomMessageParser.parse(message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }
}